﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LevelEditor.Dao;
using LevelEditor.Objects;
using LevelEditor.App;


namespace LevelEditor
{
    public partial class NewTrigger : Form
    {

        private enum State { EditingProperty, NormalCreate, AddTrigger, }

        private List<Trigger> CurrentTriggers = new List<Trigger>();
        private int CurrentSelected { get; set; }

        private Tile tileOne = null, TileTwo = null;

        private Trigger updatedTrigger;

        private State myState;

        private Trigger newTrigger;

        public NewTrigger()
        {
            InitializeComponent();
            myState = State.NormalCreate;

            updateButton.Visible = false;
            addBtn.Visible = false;

            newTrigger = new Trigger();

            LoadBehaviors();
        }

        public NewTrigger(Tile t1, Tile t2)
        {
            InitializeComponent();
            tileOne = t1;
            TileTwo = t2;
            
            myState = State.AddTrigger;
            newTrigger = new Trigger();
            updateButton.Visible = false;

            LoadBehaviors();
        }

        public NewTrigger(Trigger trigger)
        {
            InitializeComponent();
            if (trigger == null) return;
            
            txtNameTrigger.Text = trigger.Name;
            behaviorSelector.Text = trigger.MappedBehavior.Name;

            updatedTrigger = trigger;
            myState = State.EditingProperty;
            newTrigger = new Trigger();
            btnSave.Visible = false;

            createBehaviorBtn.Text = "Alter Behavior";

            LoadBehaviors();
        }

        private void LoadBehaviors()
        {
            List<Behavior> behaviors = LevelEditorDAO.GetInstance().GetAllBehavior();

            if (behaviors.Count == 0) ErrorController.ShowOkError(ErrorController.LevelEditorError.DB_REQUEST_NOBEHAVIOR);

            behaviorSelector.Items.Clear();

            for (int k = 0; k < behaviors.Count; k++)
            {
                behaviorSelector.Items.Add(behaviors[k].Name);
            }
        }

        private Label GetTitle()
        {
            Label title = new Label();
            title.Text = "Current Triggers";
            title.Font = new System.Drawing.Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);
            title.TextAlign = ContentAlignment.MiddleCenter;

            return title;
        }

        protected override void OnLoad(EventArgs e)
        {
            tablePanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 25));
            
            UpdateTriggers();
            base.OnLoad(e);
        }

        private void RemoveTriggers()
        {
            tablePanel.Controls.Clear();
        }

        private void UpdateTriggers()
        {
            CurrentTriggers = LevelEditorDAO.GetInstance().GetAllTriggers();

            tablePanel.RowCount = CurrentTriggers.Count + 1;
            tablePanel.Controls.Add(GetTitle(), 0, 0);
            for (int i = 0; i < CurrentTriggers.Count; i++)
            {
                Label l = new Label();
                l.Enabled = false;
                l.Text = CurrentTriggers[i].Name;

                tablePanel.Controls.Add(l, 0, i+1);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNameTrigger.Text))
            {
                ErrorController.ShowOkError(ErrorController.LevelEditorError.APP_NO_TRIGGER_NAME);
                return;
            }
            else
            {
                try
                {
                    if (behaviorSelector.SelectedIndex == -1)
                    {
                        ErrorController.ShowOkError(ErrorController.LevelEditorError.APP_NO_SELECTED_BEHAVIOR);
                        return;
                    }
                    newTrigger.Name = txtNameTrigger.Text;
                    if (LevelEditorDAO.GetInstance().SaveTrigger(newTrigger))
                    {
                        //inserir a trigger em ambos os tiles, caso sejam não nulos
                        Trigger t = LevelEditorDAO.GetInstance().GetTrigger(txtNameTrigger.Text);
                        if (tileOne != null && TileTwo != null)
                        {
                            tileOne.MyTrigger.Add(t);
                            TileTwo.MyTrigger.Add(t);
                            
                            Close();
                        }

                        txtNameTrigger.Clear();
                        behaviorSelector.Text = "";
                        RemoveTriggers();
                        UpdateTriggers();
                    }
                }
                catch(Exception)
                {
                    ErrorController.ShowOkError(ErrorController.LevelEditorError.APP_CREATE_TRIGGER);
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (CurrentSelected <= 0 || CurrentSelected > CurrentTriggers.Count)
            {
                ErrorController.ShowOkError(ErrorController.LevelEditorError.APP_DELETE_TRIGGER);
                return;
            }

            if (MessageBox.Show("Deseja apagar esta trigger?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                LevelEditorDAO.GetInstance().DeleteTrigger(CurrentTriggers[CurrentSelected - 1]);
                ClearSelected();
                RemoveTriggers();
                UpdateTriggers();
            }
        }

        private void SelectTrigger(object sender, EventArgs e)
        {
            Point p = Util.Util.GetPointInTablePanel(tablePanel, tablePanel.PointToClient(Cursor.Position));
            if (p.IsEmpty || p.Y == 0)
            {
                ClearSelected();
                return;
            }
            CurrentSelected = p.Y; //Row selected

            for (int row = 0; row < tablePanel.RowCount; row++)
            {
                Control control = tablePanel.GetControlFromPosition(0, row);
                if (row == CurrentSelected)
                    control.BackColor = Color.Blue;
                else
                    control.BackColor = Color.Transparent;
            }

        }

        private void ClearSelected()
        {
            if (CurrentSelected <= 0) return;
            tablePanel.GetControlFromPosition(0, CurrentSelected).BackColor = Color.Transparent;
            CurrentSelected = -1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ClearSelected();
        }

        private void updateButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNameTrigger.Text))
            {
                ErrorController.ShowOkError(ErrorController.LevelEditorError.APP_NO_TRIGGER_NAME);
                return;
            }

            try
            {
                updatedTrigger.Name = txtNameTrigger.Text;
                if (LevelEditorDAO.GetInstance().UpdateTrigger(updatedTrigger))
                {
                    Tile.CurrentSelectedTile.Deselect();

                    txtNameTrigger.Clear();
                    RemoveTriggers();
                    UpdateTriggers();

                    this.Close();
                }
            }
            catch (Exception) 
            {
                ErrorController.ShowOkError(ErrorController.LevelEditorError.APP_UPDATE_TRIGGER);
            }

        }

        private void add_Click(object sender, EventArgs e)
        {
            if (CurrentSelected <= 0 || CurrentSelected > CurrentTriggers.Count)
            {
                ErrorController.ShowOkError(ErrorController.LevelEditorError.APP_NO_SELECTED_TRIGGER);
                return;
            }

            if (myState == State.EditingProperty)
            {
                Trigger trigger = Tile.CurrentSelectedTile.MyTrigger.Find(
                delegate(Trigger t)
                {
                    return t.Name == CurrentTriggers[CurrentSelected - 1].Name;
                });

                if (trigger == null)
                {
                    Tile.CurrentSelectedTile.MyTrigger.Add(CurrentTriggers[CurrentSelected - 1]);
                }
            }
            else if (myState == State.AddTrigger)
            {

                Trigger trigger = tileOne.MyTrigger.Find(
                delegate(Trigger t)
                {
                    return t.Name == CurrentTriggers[CurrentSelected - 1].Name;
                });

                if (trigger == null)
                {
                    tileOne.MyTrigger.Add(CurrentTriggers[CurrentSelected - 1]);
                }


                Trigger trigger2 = TileTwo.MyTrigger.Find(
                delegate(Trigger t)
                {
                    return t.Name == CurrentTriggers[CurrentSelected - 1].Name;
                });

                if (trigger2 == null)
                {
                    TileTwo.MyTrigger.Add(CurrentTriggers[CurrentSelected - 1]);
                }
            }
            Close();
        }

        private void createBehaviorBtn_Click(object sender, EventArgs e)
        {
            if (this.myState == State.EditingProperty)
            {
                NewBehavior alterBehaviorDialog = new NewBehavior(updatedTrigger.MappedBehavior);
                if (alterBehaviorDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    LoadBehaviors();
                }

                return;
            }
            NewBehavior newBehaviorDialog = new NewBehavior();
            if (newBehaviorDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                LoadBehaviors();
            }

        }

        private void behaviorSelector_SelectedIndexChanged(object sender, EventArgs e)
        {
            Behavior b = LevelEditorDAO.GetInstance().getBehavior(behaviorSelector.Items[behaviorSelector.SelectedIndex].ToString());
            if (b == null)
                b = LevelEditorDAO.GetInstance().getWalkBehavior(behaviorSelector.Items[behaviorSelector.SelectedIndex].ToString());
            if (myState == State.EditingProperty)
                updatedTrigger.MappedBehavior = b;
            else newTrigger.MappedBehavior = b;
        }

    }
}
